<?php

namespace app\admin\controller\store;

use app\common\controller\Backend;
use think\Db;
use think\Log;

/**
 * 店铺管理
 *
 * @icon fa fa-circle-o
 */
class Property extends Backend
{

    /**
     * Property模型对象
     * @var \app\admin\model\store\Property
     */
    protected $model = null;
    protected $user_model = null;
    protected $order_model = null;
    protected $order_item_model = null;
    protected $withdraw_model = null;
    protected $lal_entry_model = null;
    
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\store\Property;
        $this->user_model = new \app\admin\model\User;
        $this->order_model = new \app\admin\model\order\Order;
        $this->order_item_model = new \app\admin\model\order\Item;
        $this->withdraw_model = new \app\admin\model\lal\Withdraw;
        $this->lal_entry_model = new \app\admin\model\lal\Entry;
        $this->view->assign("stateList", $this->model->getStateList());
        $this->view->assign("verifyList", $this->model->getVerifyList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("typeList", $this->model->getTypeList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

         /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->order($sort, $order)
            ->where($where)
            ->paginate($limit);

        foreach ($list as $k => $row) {
            //充值卡金额
            $where = [];
            $where['o.shop_id'] = $row['id'];
            $where['o.state'] = '6';
            $where['o.data_type'] = 'cards';
            $where['i.type'] = '4';
            $where['t.pay_way_id'] = ['in',['10','12']];
            $recharge_fee = Db::name('lal_member_entry')->alias('l')
                            ->join('wanlshop_order o','o.id=l.order_id','left')
                            ->join('wanlshop_order_item i','i.order_id=o.id','left')
                            ->join('wanlshop_pay_out_trade t', 'o.id=t.order_id', 'left')
                            ->where($where)
                            ->sum('l.bbalance');
            
            //卡项除充值卡以外的卡项金额
            $where['i.type'] = ['<>','4'];
            $cards_fee = Db::name('lal_member_entry')->alias('l')
                            ->join('wanlshop_order o','o.id=l.order_id','left')
                            ->join('wanlshop_order_item i','i.order_id=o.id','left')
                            ->join('wanlshop_pay_out_trade t', 'o.id=t.order_id', 'left')
                            ->where($where)
                            ->sum('l.bbalance');

            //购买商品/服务的总金额
            $where['o.data_type'] = 'goods';
            unset($where['i.type']);
            $goods_fee = Db::name('lal_member_entry')->alias('l')
                            ->join('wanlshop_order o','o.id=l.order_id','left')
                            ->join('wanlshop_pay_out_trade t', 'o.id=t.order_id', 'left')
                            ->where($where)
                            ->sum('l.bbalance');

            //订货订单总金额               
            $where['o.data_type'] = 'merchant';
            $where['o.state'] = ['in',['3','4','6']];
            $purchase_fee = 0;
            if ($row['id'] == 1) {
                $purchase_fee = Db::name('lal_member_entry')->alias('l')
                            ->join('wanlshop_order o','o.id=l.order_id','left')
                            ->join('wanlshop_pay_out_trade t', 'o.id=t.order_id', 'left')
                            ->where($where)
                            ->sum('l.bbalance');
            }
            

            //储值余额提现金额
            $condi = [];
            $condi['shop_id'] = $row['id'];
            $condi['status'] = 0;
            $condi['cate'] = '0';
            $stored_withdraw_total = $this->withdraw_model->where($condi)->sum('amount');

            //账户余额提现金额
            $condi['cate'] = '1';
            $account_withdraw_total = $this->withdraw_model->where($condi)->sum('amount');

            $list[$k]['c1'] = $recharge_fee;

            $list[$k]['c2'] = sprintf("%.2f", $cards_fee + $goods_fee + $purchase_fee);

            $list[$k]['c3'] = sprintf("%.2f", $stored_withdraw_total);

            $list[$k]['c4'] = sprintf("%.2f", $account_withdraw_total);

            $list[$k]['c5'] = sprintf("%.2f", $list[$k]['c1'] - $stored_withdraw_total > 0?$list[$k]['c1'] - $stored_withdraw_total:0);

            $list[$k]['c6'] = sprintf("%.2f", $list[$k]['c2'] - $account_withdraw_total > 0?$list[$k]['c2'] - $account_withdraw_total:0);

        }

        $result = ['total' => $list->total(), 'rows' => $list->items()];

        //处理统计
        if(!empty($result['rows'])){
            $filed_arr = $result['rows'];
            //处理数据
            $total = [];
            $total['c1'] = 0;
            $total['c2'] = 0;
            $total['c3'] = 0;
            $total['c4'] = 0;
            $total['c5'] = 0;
            $total['c6'] = 0;
            foreach ($filed_arr as $filed_key => $filed_val){
                $total['c1'] += $filed_val['c1'];
                $total['c2'] += $filed_val['c2'];
                $total['c3'] += $filed_val['c3'];
                $total['c4'] += $filed_val['c4'];
                $total['c5'] += $filed_val['c5'];
                $total['c6'] += $filed_val['c6'];
            }

            $total['c1'] = number_format($total['c1'],2);
            $total['c2'] = number_format($total['c2'],2);
            $total['c3'] = number_format($total['c3'],2);
            $total['c4'] = number_format($total['c4'],2);
            $total['c5'] = number_format($total['c5'],2);
            $total['c6'] = number_format($total['c6'],2);

            //设置标题
            $total['shopname'] = '合计';
            $total['type'] = '-';
            $total['status'] = 'normal';
            $total['city'] = '-';

            //追加到头部
            // array_unshift($result['rows'],$total);
           $result['rows'][] = $total;
        }
        
        return json($result);
    }

    //明细 
    public function detail()
    {
        // 设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            try {
                // 获取参数
                $shopId = (int)$this->request->get('shop_id', 0);
                $page = (int)$this->request->get('page', 1);
                $limit = (int)$this->request->get('limit', 20);
                
                // 获取分页参数
                list($where, $sort, $order, , ) = $this->buildparams();


                // 公共查询条件
                $commonWhere = function($query) use ($shopId) {
                    if ($shopId) {
                        $query->where('shop_id', $shopId);
                    }
                };
                
                // 构建表A的查询
                $fields1 = 'income AS type,id,shop_id,tratime,code,order_id,orderno,amount,charge,abalance,bbalance';
                $queryA = $this->lal_entry_model->field($fields1)->where($where)->order($sort, $order);

                // 构建表B的查询
                $fields2 = 'withdraw  AS type,id,shop_id,createtime AS tratime,code,NULL AS order_id,NULL AS orderno,amount,NULL AS charge,NULL AS abalance,NULL AS bbalance';
                $queryB = $this->withdraw_model->field($fields2)->where($where)->order($sort, $order);

                // 添加店铺ID过滤条件
                if ($shopId) {
                    $queryA->where($commonWhere);
                    $queryB->where($commonWhere);
                }

                // 使用union方法进行联合查询
                $unionQuery = $queryA->union($queryB, true);
                
                // 计算偏移量
                $offset = ($page - 1) * $limit;
                
                // 执行查询并获取分页数据
                $list = $unionQuery->limit($offset, $limit)->select();

                // 统计总记录数
                $count = $unionQuery->count();

                // 返回分页数据
                return json([
                    'total' => $count,
                    'rows' => $list->toArray()
                ]);
            } catch (\Exception $e) {
                // 记录错误日志
                Log::error("UNION查询错误: " . $e->getMessage());
                Log::error("错误行数: " . $e->getline());
                Log::error("SQL: " . $unionQuery->getLastSql()); // 获取SQL语句用于调试
                
                return json([
                    'code' => 500,
                    'msg' => '查询失败，请重试'
                ]);
            }
        }

        return $this->view->fetch();
    }
}
